package leetcode;

import java.util.Stack;

public class DecodeString {

	public static void main(String[] args) {
		DecodeString object = new DecodeString();
		String s = "10[leetco]";
		System.out.println("res: " + object.decodeString(s));
	}
	
	public String decodeString(String s) {
		System.out.println("cur S: " + s);
        if(s == null || s.indexOf('[') == -1){
        	return s;
        }
        int length = s.length();
        Stack<Integer> stack = new Stack<>();
        StringBuilder sbBuilder = new StringBuilder();
        String next = "";
        
        //错了, 数字可能不止一位
        for(int i = 0; i < length; i++){
        	char c = s.charAt(i);
        	int repeat = 0;
        	if(Character.isDigit(c)){
        		repeat = c - '0';
        		System.out.println("curNum: " + repeat);
        		int index = i + 1;
        		for(; index < length; index++){
        			char cur = s.charAt(index);
        			if(cur != '['){
        				repeat = repeat * 10 + cur - '0';
        			}else{
        				break;
        			}
        		}
        		for(int j = index; j < length; j++){
        			char cur = s.charAt(j);
        			if(cur == ']'){
        				if(stack.size() == 1){
        					next = decodeString(s.substring(stack.pop() + 1, j));
        					System.out.println("next: "  + next);
        					i = j;
        					break;
        				}else{
        					stack.pop();
        				}
            		}else if(cur == '['){
            			stack.push(j);
            		}
        		}
        	}else{
        		sbBuilder.append(c);
        	}
        	System.out.println("i : " + i + " : " + repeat);
        	for(int j = 0; j < repeat; j++){
        		sbBuilder.append(next);
        	}
        }
        return sbBuilder.toString();
    }
}
